<template>
  <div class="ui segment">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="导入操作">
          <a-card title="财务帐单导入及对帐" :bordered="false">
            <a-row v-show="currentTab === 0">
              <a-col :span="6">
                <div>
                  <a-upload
                      list-type="text"
                      action=""
                      :multiple="true"
                      :file-list="fileList_finance_check"
                      :beforeUpload="beforeUpload"
                      accept=".xlsx,.xls"
                      @remove="removeFile">
                    <a-button>
                      <UploadOutlined />
                      选择文件
                    </a-button>
                  </a-upload>
                </div>
              </a-col>
              <a-col :span="3" :offset="3">
                <a-button type="primary" :loading="loading" @click="genCheckList"><FileAddOutlined/>生成核对信息</a-button>
              </a-col>
              <a-col :span="2" :offset="1">
                <a-button type="primary" @click="reset">重置</a-button>
              </a-col>
            </a-row>
          </a-card>
          <a-card :bordered="false">
            <a-steps class="steps" :current="currentTab">
              <a-step title="帐务信息核对" />
              <a-step title="确认入系统" />
              <a-step title="完成" />
            </a-steps>
            <div class="content" v-show="checkLoaded">
              <step1 v-if="currentTab === 0" :checkResult="checkResult" :check-data="checkData" @nextStep="nextStep" @prevStep="prevStep"/>
              <step2 v-if="currentTab === 1" :checkResult="checkResult" :check-data="checkData" :traders="checkBillStore.groupedTradePartners"
                     :loading="loading" @nextStep="nextStep" @prevStep="prevStep" />
              <step3 v-if="currentTab === 2" @prevStep="prevStep" @finish="finish" />
            </div>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="2" tab="已导入明细" force-render>
          <div>
            <a-row :gutter="24">
              <a-col :span="7">
                <a-form-item label="帐单日期" :labelCol="{span:8}" :wrapperCol="{span:24 - 8}">
                  <a-range-picker
                      allowClear
                      v-model="queryParams.bill_date"
                      :format="dateFormat"
                      :ranges="dateRange"
                      :value-format="dateFormat"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="导入日期" :labelCol="{span:8}" :wrapperCol="{span:24 - 8}">
                  <a-range-picker
                      allowClear
                      v-model="queryParams.update_date"
                      :format="dateFormat"
                      :ranges="dateRange"
                      :value-format="dateFormat"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-input allowClear v-model="queryParams.bill_no" placeholder="主单号" />
                </a-form-item>
              </a-col>
              <a-col :span="2" :offset="1">
                <a-form-item>
                  <a-button @click.prevent="search" :loading="loading" type="default">查询</a-button>
                </a-form-item>
              </a-col>
            </a-row>
            <!-- table区域-begin -->
            <a-row :gutter="24">
              <a-card style="width: 90%" >
                <a-table
                    ref="table"
                    size="small"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    @change="(pagination) => { ipagination = pagination; queryList(); }"
                    :pagination="ipagination"
                    :loading="loading"
                >
                  <template #billNoLink="{ text }">
                    <router-link :to="{ path: '/finance/checkBill', query: { billNo: text } }"> {{ text }} </router-link>
                  </template>
                  <template #upClient="{ text, record }">
                    <div class="editable-cell">
                      <div v-if="editableData[record.bill_no]" class="editable-cell-input-wrapper">
                        <a-select style="width: 8vw"
                                  allowClear
                                  show-search
                                  placeholder="上游客户"
                                  :filter-option="false"
                                  @search="(v) => queryParams.searchText[record.bill_no] = v"
                                  @change="save(record.bill_no, editableData[record.bill_no].id_trade_partner)"
                                  :options="customizedFilterOptions(queryParams.searchText[record.bill_no], checkBillStore.groupedTradePartners)"
                                  v-model:value="editableData[record.bill_no].id_trade_partner"/>
                        <check-outlined class="editable-cell-icon-check" @click="save(record.bill_no, editableData[record.bill_no].id_trade_partner)" />
                      </div>
                      <div v-else class="editable-cell-text-wrapper">
                        {{ checkBillStore.dictObj.id_trade_partner[text] || ' ' }}
                        <edit-outlined class="editable-cell-icon" @click="edit(record.bill_no)" />
                      </div>
                    </div>
                  </template>
                </a-table>
              </a-card>
            </a-row>
          </div>
        </a-tab-pane>
      </a-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { deleteAction, downFile, getAction, postAction, postDownFile } from "@/utils/request";
import moment from "moment";
import { ElMessage } from 'element-plus';
import {Button, Upload} from 'ant-design-vue';
import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';
import Step1 from './FinaceCheckStep/Step1.vue';
import Step2 from './FinaceCheckStep/Step2.vue';
import Step3 from './FinaceCheckStep/Step3.vue';
import useCheckBillStore from "@/store/modules/checkBill.js";
import {customizedFilterOptions} from "@/utils/my.js";
import { cloneDeep } from 'lodash-es';
const AButton = Button, AUpload = Upload


//dict
const checkBillStore = useCheckBillStore()
checkBillStore.getTradePartner()
checkBillStore.getPortsAndClient()

// 响应式数据
const loading = ref(false);
const fileList_finance_check = ref([]);
const checkResult = ref({});
const checkData = ref({});
const checkLoaded = ref(false);
const url = {
  excel_loaded_for_comparison: "/yg/excel_loaded_for_comparison",
  query_for_comparison: "/yg/query_for_comparison",
  update_comparison: "/yg/update_comparison"

}
const currentTab = ref(0);
const activeKey = ref("1");
const dateFormat = ref('YYYY-MM-DD');
const queryParams = ref({
  bill_date: [],
  update_date: [],
  bill_no: "",
  id_trade_partner: {},
  searchText: {}
});
const dateRange = ref({
  今天: [moment(), moment()],
  一周内: [moment().add(-6, 'day'), moment()],
  本月: [moment().startOf('month'), moment().endOf('month')],
  上个月: [moment(new Date()).subtract(1, 'months').startOf('month'), moment(new Date()).subtract(1, 'months').endOf('month')],
  近三个月: [moment(new Date()).subtract(2, 'months').startOf('month'), moment().endOf('month')]
});
const ipagination = ref({
  current: 1,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '50', '100'],
  showTotal: (total, range) => {
    return `${range[0]}-${range[1]} 共${total}条`;
  },
  showQuickJumper: true,
  showSizeChanger: true,
  total: 0
});
const dataSource = ref([]);
const table = ref(null);
const columns = ref([
  {
    title: '主单号',
    dataIndex: 'bill_no',
    slots: { customRender: 'billNoLink' }
  },
  {
    title: '上游客户',
    dataIndex: 'id_trade_partner',
    align: 'center',
    slots: { customRender: 'upClient' }
  },
  {
    title: '贸易方[系统]',
    dataIndex: 'id_partner_client',
    align: 'center',
    customRender: ({text}) => {
      return checkBillStore.dictObj.id_trade_partner[text]
    }
  },
  {
    title: '日期',
    dataIndex: 'bill_date',
    customRender: (t, r, index) => {
      return t && moment(t).format("YYYY-MM-DD");
    }
  },
  {
    title: '总金额',
    dataIndex: 'total_amount',
    align: 'right',
    customRender: ({text:t}) => {
      return t ? t.toFixed(2) : "";
    }
  },
  {
    title: '总金额[系统]',
    dataIndex: 'total_amount_sys',
    align: 'right',
    customRender: ({text:t}) => {
      return t ? t.toFixed(2) : "";
    }
  },
  {
    title: '计费重量',
    dataIndex: 'weight_for_fee',
    align: 'right',
    customRender: ({text:t, record:r}) => {
      if (t && r.weight_for_fee_sys !== t) {
        return {
          children: `<span class="ant-table-row-selected rowBeExec">${t}</span>`,
          props: {
            innerHTML: true
          }
        };
      } else {
        return t;
      }
    }
  },
  {
    title: '计费重量[系统]',
    dataIndex: 'weight_for_fee_sys',
    align: 'right'
  },
  {
    title: '导入人',
    dataIndex: 'update_by'
  },
  {
    title: '最后更新时间',
    dataIndex: 'update_time',
    customRender: ({text:t}) => {
      return t && moment(t).format("YYYY-MM-DD");
    }
  }
]);
const editableData = reactive({});
const edit = (bill_no) => {
  console.log("edit....")
  editableData[bill_no] = cloneDeep(dataSource.value.find(item => bill_no === item.bill_no));
  //console.error("  editableData[bill_no]:",editableData[bill_no])
};
const save = (bill_no, id_trade_partner) => {
  changeUpClient(bill_no, id_trade_partner)
  Object.assign(dataSource.value.filter(item => bill_no === item.bill_no)[0], editableData[bill_no]);
  delete editableData[bill_no];
};

// 方法
const changeUpClient = (bill_no, id_trade_partner) => {
  if (!id_trade_partner || !bill_no) {
      ElMessage.error("请选择下游客户！");
      return
  }
  postAction(url.update_comparison, { bill_no, id_trade_partner })
      .then((res) => {
        if (res && res.success) {
          ElMessage.success("保存成功！");
        } else {
          ElMessage.error("保存失败！");
        }
      })
      .catch((err) => {
        ElMessage.error("保存失败！");
        console.error(err && err.message);
      });
};

const search = () => {
  ipagination.value = {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30', '50', '100'],
    showTotal: (total, range) => {
      return `${range[0]}-${range[1]} 共${total}条`;
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  };
  queryList();
};

const queryList = async () => {
  console.log("get bill list ...");
  loading.value = true;
  const { current, pageSize } = ipagination.value;
  const { update_date, bill_date, bill_no } = queryParams.value;
  try {
    const res = await postAction(url.query_for_comparison, { current, pageSize, update_date, bill_date, bill_no });
    if (res.success && typeof res.data === 'object' && res.data !== null) {
      dataSource.value = res.data.records;
      ipagination.value.total = res.data.total;
      console.log(dataSource.value);
    }
  } catch (err) {
    ElMessage.error('查询失败！');
  } finally {
    loading.value = false;
  }
};

const nextStep = () => {
  if (currentTab.value < 2) {
    currentTab.value += 1;
  }
};

const prevStep = () => {
  if (currentTab.value > 0) {
    currentTab.value -= 1;
  }
};

const finish = (args) => {
  console.log("finish:", args);
  reset();
  if (args === 1) {
    queryParams.value.update_date = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')];
    activeKey.value = "2";
  }
};

const reset = () => {
  fileList_finance_check.value = [];
  loading.value = false;
  checkData.value = {};
  checkResult.value = {};
  currentTab.value = 0;
  checkLoaded.value = false;
};

const genCheckList = () => {
  loading.value = true;
  if (fileList_finance_check.value.length === 0) {
    ElMessage.error(`请先选择帐单excel文件！`);
    loading.value = false;
    return;
  }
  const formData = new FormData();
  fileList_finance_check.value.forEach((file) => {
    formData.append('files', file);
  });
  postAction(url.excel_loaded_for_comparison, formData)
      .then((res) => {
        if (!res) {
          ElMessage.warning("文件解析失败！");
          return;
        }
        parseData(res.data);
        console.error(res.data);
        checkLoaded.value = true;
      })
      .catch((err) => {
        console.error(err.message);
      })
      .finally(() => {
        loading.value = false;
      });
};

const parseData = (dct) => {
  checkData.value = {};
  for (const key in dct) {
      checkData.value[key] = JSON.parse(dct[key]);
  }
  console.error("checkData:", checkData.value);
};

const removeFile = (file) => {
  const position = fileList_finance_check.value.findIndex((f) => f.name === file.name);
  console.log("position:", position);
  if (position > -1) {
    fileList_finance_check.value.splice(position, 1);
  }
};

const beforeUpload = (file) => {
  const fileType = file.type;
  if (fileType.indexOf('excel') < 0 && fileType.indexOf('sheet') < 0) {
    ElMessage.error('请上传Excel表格文件');
    return false;
  }
  if (!fileList_finance_check.value.find((f) => f.name === file.name)) {
    fileList_finance_check.value.push(file);
  }
  if (fileList_finance_check.value.length > 10) {
    ElMessage.error('一次上传，不能超过10个文件');
    return false;
  }
  return true;
};

// 监听 activeKey 变化
watch(activeKey, (newValue) => {
  loading.value = false;
  if (newValue === "2") {
    queryList();
  }
});

// 生命周期钩子
onMounted(() => {
  console.log("start mounting...");
  console.log("mounted...");
});
</script>


<style lang="less">
.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}
.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>